import axios from "axios"
import cookie from 'js-cookie'
import router from "../router";

export function request(config) {
    const instance = axios.create({
        timeout: 5000
    })

    //配置拦截器
    instance.interceptors.request.use(
        config => {  //每次发送请求使用这个拦截器
            let loginUrl = ["/movie/wantSee","/movie/comment/giveLike","/order/submitOrder"]
            let flag = true;
            let url = config.url;
            for (let i = 0; i < loginUrl.length; i++) {
                let number = url.indexOf(loginUrl[i]);
                if (number == 0) {
                    flag = false
                }
            }
            //判断是否需要登录
            if (flag || cookie.get('userInfo')) {
                //每次发送请求 在请求头带上token
                if (cookie.get('token')) {
                    config.headers['token'] = cookie.get('token');
                }
                return config
            } else {
                router.push("/login")
                return
            }
        },
        err => {
            return Promise.reject(err);
        }
    )

    instance.interceptors.response.use(config => {
        if (config.data.code == "0") {
            return config.data;
        } else {
            return Promise.reject(config)
        }
    }, err => {
        return Promise.reject(err)
    })

    //发送网络请求
    return instance(config)

}
